package com.summer.authentication.service.impl;

import com.alibaba.fastjson.JSON;
import com.summer.authentication.mapper.XcUserMapper;
import com.summer.authentication.model.AuthParams;
import com.summer.authentication.model.dto.XcUserDto;
import com.summer.authentication.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private XcUserMapper userMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 获取登录提交的信息（包括账号密码、授权码、sms等）
        System.out.println("logging-info=" + s);
        AuthParams authParams = null;
        try {
            authParams = JSON.parseObject(s, AuthParams.class);
        } catch (Exception e) {
            throw new RuntimeException("登录信息不不符合要求");
        }

        // 获取信息无误后调用统一认证接口进行认证
        AuthService authService = applicationContext.getBean(authParams.getAuthType(), AuthService.class);
        XcUserDto xcUserDto = authService.authExecute(authParams);

        // 认证成功后返回UserDetails，生成jwt令牌
        return getUserDetailsByUserDto(xcUserDto);
    }

    private UserDetails getUserDetailsByUserDto(XcUserDto xcUserDto) {
        // 将password置空，以免令牌中有敏感信息
        String password = xcUserDto.getPassword();
        xcUserDto.setPassword(null);

        // 将userDto转为json存入jwt令牌
        String userJson = JSON.toJSONString(xcUserDto);

        // 根据数据库查出权限列表
        List<String> permissionList = userMapper.getPermissionByUid(xcUserDto.getId());
        String[] permissionArrays = permissionList.toArray(new String[0]);

        // 返回UserDetails对象
        return User.withUsername(userJson).password(password).authorities(permissionArrays).build();
    }


}
